package com.xcms.news;


import com.xcms.test.ResultFs;
import com.xcms.util.JDBCHelper;
import com.xcms.util.Page;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：xx
 * @date ：Created in 2020/5/22 9:30
 * @description：
 * @modified By：
 */
public class NewsDao {
    public static boolean insert(News news){
        String sql="INSERT INTO news(title,content,url) VALUES (?,?,?)";
        int cout= JDBCHelper.update(sql,news.getTitle(),news.getContent(),news.getUrl());
        return cout>0;
    }
    public static void delete(int id){
        String sql="delete from news where id = ?";
        JDBCHelper.delete(sql,id);
    }


    public static boolean update(int id, String title) {
        String sql="update news set title = ? where id =?";
        int result=JDBCHelper.update(sql,id,title);
        return result>0;
    }


    public static Page<News> getPage(int pageSize,int currPage){
        Page<News> page=null;
        int totalCount=0;
        String sql="SELECT count(1) from news";
        try {
            //1.获取总条数
            ResultSet rs=JDBCHelper.query(sql);
            if(rs.next())
            {
                totalCount=rs.getInt(1);
            }
            page=new Page<News>(totalCount,pageSize,currPage);
            //2. 设置当前页的数据
            sql="SELECT * FROM news ORDER BY id DESC LIMIT "+page.getCurrpageindex()+","+pageSize;
            rs=JDBCHelper.query(sql);
            List<News> news= ResultFs.getList(rs,"com.xcms.news.News");
            page.setRecords(news);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        finally {
            JDBCHelper.close();
        }
        return page;
    }

    public static List<News> getLatestNews() {
        List<News> news =new ArrayList<>();
        try {
            ResultSet rs= JDBCHelper.query("SELECT * FROM news ORDER BY id DESC LIMIT 0,5");
            news= ResultFs.getList(rs,"com.xcms.news.News");
     } catch (Exception e) {
        System.out.println("获取信息数据出错"+e.getMessage());
    } finally {
        JDBCHelper.close();
    }
        return  news;
    }


}
